<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="formVisible = true">添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="打卡名称" value="1"></el-option>
              <el-option label="创建者" value="2"></el-option>
              <el-option label="批次" value="3"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok"/>
      </div>
    </div>
    <el-table stripe style="width: 100%"  border fit highlight-current-row ref="tableDataRef" :data="tableData" :key="key">
      <el-table-column v-if="colData[0].istrue" min-width="50" align="center" prop="id" label="ID"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="50" align="center" prop="admin_name" label="创建者"></el-table-column>
      <el-table-column v-if="colData[2].istrue"  min-width="100" align="center" prop="batch" label="分发批次">
        <template slot-scope="scope">
          <p v-for="(item,index) in scope.row.batch" :key="item.id" style="margin: 0;padding: 0">{{item.batch}}</p>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="70" align="center" prop="name" label="名称" show-overflow-tooltip></el-table-column>
      <el-table-column v-if="colData[4].istrue" min-width="60" align="center" prop="frequency" label="打卡频次">
        <template slot-scope="scope">
          <p v-show="scope.row.frequency==1">每天</p>
          <p v-show="scope.row.frequency==2">每周</p>
          <p v-show="scope.row.frequency==3">每半月</p>
          <p v-show="scope.row.frequency==4">每月</p>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[5].istrue" min-width="60" align="center" prop="process"  label="当前进程"></el-table-column>
      <el-table-column v-if="colData[6].istrue" min-width="140" align="center" prop="create_time" label="打卡周期">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column v-if="colData[7].istrue" min-width="70" align="center" prop="type" label="授权打卡方式">
        <template slot-scope="scope">
          <p v-show="scope.row.type==1">纯打卡</p>
          <p v-show="scope.row.type==2">文字</p>
          <p v-show="scope.row.type==3">文字+图片</p>
          <p v-show="scope.row.type==4">文字+录音</p>
          <p v-show="scope.row.type==5">文字+视频</p>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[8].istrue" min-width="140" align="center" prop="create_time" label="创建日期">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column v-if="colData[9].istrue" min-width="70" align="center" prop="rate" label="综合打卡率">
        <template slot-scope="scope">
          <p>{{scope.row.rate}}%</p>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[10].istrue" min-width="80" align="center" prop="notClockNum"  label="本轮未打卡人数">
        <template slot-scope="scope">
          <p style="color: #0079ff" @click="openAllSn(scope.row.id)">{{scope.row.notClockNum}}</p>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="200" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="openEdit(scope.row)">编辑</el-button>
            <el-button size="mini" @click="delHomeWork(scope.row.id)">删除</el-button>
            <el-button size="mini" type="primary" @click="toClockDetail(scope.row.id)">查看</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
                     layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>

    <el-dialog title="待提交人数" :visible.sync="noReadSnVisible">
      <el-table :data="noReadSnData" border stripe>
        <el-table-column property="value" align="center" label="SN" min-width="150"></el-table-column>
        <el-table-column property="batch" align="center" label="批次" ></el-table-column>
        <el-table-column property="classlevel" align="center" label="班级"></el-table-column>
        <el-table-column property="sno" align="center" label="学号" ></el-table-column>
        <el-table-column property="realname" align="center" label="姓名" ></el-table-column>
        <el-table-column property="phone" align="center" label="监护人1"></el-table-column>
        <el-table-column property="phone_two" align="center" label="监护人2"></el-table-column>
      </el-table>
      <div class="paging">
        <el-pagination :current-page.sync="noReadQuery.startSize" background @size-change="noReadSizeChange"
                       @current-change="noReadCurrentChange" :page-sizes="[10, 50, 100, 200]"
                       layout="total, sizes, prev, pager, next, jumper" :total="noReadTotal" :page-size="noReadQuery.pageSize">
        </el-pagination>
      </div>
    </el-dialog>

    <!-- 添加弹窗 -->
    <el-dialog :title="editSubjects== true ? '编辑打卡': '创建打卡' " :visible.sync="formVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="40%" @close="addFormclose">
      <el-form :model="addForm"  ref="ruleForm" :rules="rules" class="diolog_adapt" style="width: 600px" >
        <el-form-item label="批次:" label-width="130px" prop="batch">
          <el-select v-model="addForm.batch"  multiple filterable placeholder="请选择批次" clearable>
            <el-option
              v-for="item in batchArr"
              :key="item.id"
              :label="item.batch"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="打卡名称:" label-width="130px" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入名称" maxlength="40" clearable></el-input>
        </el-form-item>
        <el-form-item label="打卡周期:" label-width="130px" prop="cycle_time">
          <div class="block">
            <el-date-picker
              v-model="addForm.cycle_time"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              value-format="timestamp"
              :default-time = "['00:00:00','23:59:59']"
              end-placeholder="结束日期">
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="打卡频次:" label-width="130px" prop="frequency">
          <el-select v-model="addForm.frequency" placeholder="请选择">
            <el-option label="每天" :value="1"></el-option>
            <el-option label="每周" :value="2"></el-option>
            <el-option label="每半月" :value="3"></el-option>
            <el-option label="每月" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="打卡时段:" label-width="130px" prop="clock_time">
          <el-time-picker
            is-range
            v-model="addForm.clock_time"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="timestamp"
            placeholder="选择时间范围">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="打卡内容:" label-width="130px" prop="content">
          <el-input type="textarea" v-model="addForm.content" placeholder="请输入打卡内容" clearable></el-input>
        </el-form-item>
        <el-form-item label="允许补卡:" label-width="130px" prop="allow_restock">
          <el-select v-model="addForm.allow_restock" placeholder="请选择">
            <el-option label="允许" :value="1"></el-option>
            <el-option label="不允许" :value="-1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="授权打卡方式:" label-width="130px" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择">
            <el-option label="纯打卡" :value="1"></el-option>
            <el-option label="文字" :value="2"></el-option>
            <el-option label="文字+图片" :value="3"></el-option>
            <el-option label="文字+录音" :value="4"></el-option>
            <el-option label="文字+视频" :value="5"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" size="mini" round @click="editHomework('ruleForm')">确 定
        </el-button>
        <el-button v-else type="primary" @click="addClock('ruleForm')" size="mini" round>确定</el-button>
      </div>
    </el-dialog>

    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>

</template>

<script>
  import objectable from "@/utils/objectable.js";
  import dynamicTable from "@/components/DynamicTable";
  import deleteDialog from "@/components/deleteDialog";
  import tableMini from '@/utils/tableMini.js'
  import {
    addClock, queryClock, editClock, delClock, getNoClockSn
  } from "@/api/launcherMade";
  import {getBatchTwo} from "@/api/equipment";

  export default {
    mixins: [tableMini],
    components: {dynamicTable, deleteDialog},
    data() {
      return {
        key: 1,
        colData: [], //动态控制table
        checkboxVal: ["ID", "创建者", "批次", "类型", "打卡名称", "打卡频次", "当前进程", "打卡周期", "授权打卡方式", "创建日期", "综合打卡率", "本轮未打卡人数"],
        searchTable: "",
        select: "", //搜索条件
        tableData: [],
        listQuery: {
          startSize: 1,
          pageSize: 10,
          userId: localStorage.getItem("ID"),
        },
        addForm: {
          batch: [],  //批次
          name: '',  //名称
          cycle_time: [], //打卡周期
          frequency: '',  //打卡频次
          clock_time:[1699574400000,1699610400000], //打卡时段
          content: '',  //打卡内容
          allow_restock: 1,  //是否允许补卡
          type: '',  //打卡方式
        },
        formVisible: false,
        rules: {
          type: [{ required: true, message: '请选择打卡方式', trigger: 'change' }],
          batch: [{ required: true, message: '请选择批次', trigger: 'change' }],
          cycle_time: [{required: true, message: '请输入打卡周期', trigger: 'blur'}],
          clock_time: [{required: true, message: '请输入打卡周期', trigger: 'blur'}],
          frequency: [{ required: true, message: '请选择打卡频次', trigger: 'blur' }],
          name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
          allow_restock: [{ required: true, message: '请选择是否允许打卡', trigger: 'blur' }],
        },
        editSubjects: false,
        deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
        batchArr: [],
        noReadSnVisible: false,
        noReadSnData: [],
        noReadQuery: {
          startSize: 1,
          pageSize: 10,
          id: undefined
        },
        noReadTotal: 0,
      }
    },
    created() {
      this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
      this.queryClockData()
      this.getBatchTwo()
    },
    methods: {
      Refresh() {
        this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), name: undefined, create_time: undefined}
        this.queryClockData()
      },
      openAllSn(id) {
        this.noReadSnVisible=true
        this.noReadQuery.id=id
        this.getNoClockSnData()
      },
      getNoClockSnData() {
        getNoClockSn(this.noReadQuery).then(res => {
          this.noReadSnData = res.data
          this.noReadTotal = res.total
        }).catch(err => {
          this.noReadSnData = []
          this.noReadTotal = 0
        })
      },
      toClockDetail(id) {
        this.$router.push({name:'contentManage/clockDetail', query:{id: id}});
      },
      //搜索,1:课程名称
      idnameSearch() {
        if (!this.select) return this.$message.warning("请先选择查询条件");
        this.listQuery = this.$options.data().listQuery
        switch (this.select) {
          case '1':
            this.listQuery.name = this.searchTable
            this.queryClockData();
            break;
          case '2':
            this.listQuery.admin_name = this.searchTable
            this.queryClockData();
            break;
          case '3':
            this.listQuery.batch = this.searchTable
            this.queryClockData();
            break;
        }
      },
      getBatchTwo() {
        getBatchTwo({ userId: localStorage.getItem("ID") }).then(res => {
          this.batchArr = res.data
        }).catch(err => {
          this.batchArr = []
        })
      },
      openEdit(row) {
        this.formVisible = true
        this.editSubjects=true
        this.isVisible = row.notice_type === 3
        this.addForm = {
          id: row.id,
          batch: row.batchArr,  //批次
          name: row.name,  //名称
          cycle_time: [row.cycle_start*1000, row.cycle_end*1000], //打卡周期
          frequency: row.frequency,  //打卡频次
          clock_time:[row.clock_start*1000,row.clock_end*1000], //打卡时段
          content: row.content,  //打卡内容
          allow_restock: 1,  //是否允许补卡
          type: row.type,  //打卡方式
        }
      },
      addClock(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let addForm = JSON.parse(JSON.stringify(this.addForm))
            addForm.last_ip = sessionStorage.getItem("Ip")
            addForm.userId = localStorage.getItem("ID")
            addClock(addForm).then(res => {
              this.$message.success(res.msg)
              this.queryClockData()
              this.formVisible = false
            }).catch(err => {
            })
          } else {
            return false;
          }
        });
      },
      queryClockData() {
        queryClock(this.listQuery).then(res => {
          this.tableData = res.data
          this.total = res.total
        }).catch(err => {
          this.tableData = []
          this.total = 0
          this.$message.error(res.msg)
        })
      },
      editHomework(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let editForm = JSON.parse(JSON.stringify(this.addForm))
            editForm.last_ip = sessionStorage.getItem("Ip")
            editForm.userId = localStorage.getItem("ID")
            editClock(editForm).then(res => {
              this.$message.success(res.msg)
              this.formVisible = false
              this.queryClockData()
            }).catch(err => {
            })
          } else {
            return false;
          }
        });
      },

      delHomeWork(id) {
        this.deleteDialogs.show = true
        this.deleteDialogs.deleteId = id
      },
      //删除按钮事件
      deleteEvents() {
        let params = {
          userId: localStorage.getItem("ID"),
          last_ip: sessionStorage.getItem("Ip"),
          id: this.deleteDialogs.deleteId,
        }
        delClock(params).then(res => {
          if(res.code==200){
            this.$message.success(res.msg)
          }else{
            this.$message.error(res.msg)
          }
          this.queryClockData()
        }).catch(err => {
          console.log("请求失败", err)
        })
      },
      //分页
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.queryClockData()
      },
      handleCurrentChange(val) {
        this.listQuery.startSize = val
        this.queryClockData()
      },
      noReadSizeChange(val) {
        this.noReadQuery.pageSize = val
        this.getNoClockSnData()
      },
      noReadCurrentChange(val) {
        this.noReadQuery.startSize = val
        this.getNoClockSnData()
      },
      //下拉动态table子组件
      alterCheckbok(key, conte) {
        this.key = key;
        this.colData.filter(i => {
          if (conte.indexOf(i.title) != -1) {
            i.istrue = false;
            this.$nextTick(() => {
              this.$refs.tableDataRef.doLayout();
            });
          } else {
            i.istrue = true;
            this.$nextTick(() => {
              this.$refs.tableDataRef.doLayout();
            });
          }
        });
      },
      //编辑添加表单关闭事件
      addFormclose() {
        this.editSubjects=false
        this.$nextTick(() => {
          this.addForm = this.$options.data().addForm
        })
      },
    }
  }
</script>



